<template>
    <div class="fullPage">
        <div class="pageHeader">
            <div class="title">
                <i :class="ui.title.icon"></i> <span>{{ui.title.name}}</span> / <span>{{ui.title.localName}}</span>
            </div>
            <div class="filter"></div>
            <div class="acs">
                <ul class="lstAcs">
                    <li><el-button type = "text" @click="refresh"><i class="fa fa-refresh"></i> refresh</el-button></li>
                </ul>
            </div>
        </div>
        <div class="pageBody">
            <div class="tabGrid">
                <div class="tabPan fullHeight">
                    <div class="tabTools">
                        <div class="select">
                            <el-select  v-model="eventIndex"  size="mini" @change="refresh">
                                <el-option
                                    v-for="(item,evIndex) in events"
                                    :key="evIndex"
                                    :label="item.caption"
                                    :value="evIndex">
                                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.localName }}</span>
                                </el-option>
                            </el-select>

                        </div>
                        <div class="acs">
                            <el-button type="mini">
                                <i class="fa fa-refresh"></i> refresh
                            </el-button>
                            <el-button type="mini">
                                <i class="fa fa-check-square"></i> all
                            </el-button>
                            <el-button type="mini">
                                <i class="fa fa-square-o"></i> clear
                            </el-button>
                            <el-button type="mini">
                                <i class="fa fa-times"></i> delete
                            </el-button>
                        </div>
                    </div>
                    <div class="tabMain" id="tabRegCompMain">
                        <el-table
                            ref="regCompTable"
                            :data="regComps"
                            tooltip-effect="dark"
                            style="width: 100%"
                            :height="ui.regCompTabHeight"
                        >
                            <el-table-column      type="selection"      width="55"></el-table-column>
                            <el-table-column label="Order" prop="order" width="60"></el-table-column>
                            <el-table-column label="Delegation" prop="delegation" width="180"></el-table-column>
                            <el-table-column label="Code" prop="code" width="80"></el-table-column>
                            <el-table-column label="Name" prop="name" width="180"></el-table-column>
                            <el-table-column label="LocalName" prop="localName" width=""></el-table-column>
                            <el-table-column
                                fixed="right"
                                label="Action"
                                width="120">
                                <template slot-scope="scope">
                                    <div class="tabRowAcs">
                                        <el-button
                                            @click.native.prevent="showDlg(scope.row)"
                                            type="text" >
                                            edit
                                        </el-button>
                                        <el-button
                                            @click.native.prevent="showDlg(scope.row)"
                                            type="text" >
                                            delete
                                        </el-button>
                                    </div>
                                </template>
                            </el-table-column>

                        </el-table>

                    </div>
                    <div class="tabFooter">
                        <div class="footerAcs">
                            <div class="title">Total : <b>{{regComps.length}}</b></div>
                        </div>
                    </div>
                </div>
                <div class="tabPan fullHeight">
                    <div class="tabTools">
                        <div class="select">
                            <el-select v-model="delegationIndex"  size="mini" @change="refresh">
                                <el-option
                                    v-for="(item,deIndex) in delegations"
                                    :key="deIndex"
                                    :label="item.caption"
                                    :value="deIndex">
                                    <span style="float: left">{{ item.code }}</span>
                                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.localName }}</span>
                                </el-option>
                            </el-select>

                        </div>
                        <div class="genderList" v-show="showGender">
                        </div>
                        <div class="acs">
                        </div>
                    </div>
                    <div class="tabMain" id="tabAthleteMain">
                        <el-table
                            ref="athletaTable"
                            :data="athletes"
                            tooltip-effect="dark"
                            style="width: 100%"
                            :height="ui.athleteTabHeight"
                        >
                            <el-table-column      type="selection"      width="55"></el-table-column>
                            <el-table-column label="Code" prop="code" width="80"></el-table-column>
                            <el-table-column label="Bib" prop="bIBCODE" width="80"></el-table-column>
                            <el-table-column label="Gender" prop="gender" width="70"></el-table-column>
                            <el-table-column label="Name" prop="name" width=""></el-table-column>

                        </el-table>
                    </div>
                    <div class="tabFooter">
                        <div class="footerAcs">
                            <div class="title"></div>
                            <div class="acs">
                            <el-button type="primary" size="mini" @click="addRegComp">
                                <i class="fa fa-plus"></i> add
                            </el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
class TRegComp {
  constructor () {
    this.sys = null
    this.sqls = {
      addSingleRegComps: 'addSingleRegComps',
      addSingleRegComps_check: 'addSingleRegCompsCheck',
      addTeamRegComps: 'addTeamRegComps',
      addTeamRegComps_checkDelegationId: 'addTeamRegComps_checkDelegationId',
      addDoubleRegComps: 'addDoubleRegComps',
      getRegCompId: 'getRegCompId',
      addRegCompMembers: 'addRegCompMembers'
    }
  }

  addRegComps (eventId, delegation, aths) {
    var me = this
    var resStatus = {
      status: 0
    }
    return new Promise((success, faild) => {
      try {

      } catch (error) {
        success(resStatus)
      }
    })
  }

  addSingleRegComps (eventId, athIds) {
    var me = this
    var resStatus = {
      status: 0,
      regIds: {}
    }
    return new Promise((success, faild) => {
      try {
        var ind = 0
        resStatus.regIds = athIds.map(a => {
          var r = {}
          r[a] = 0
          return r
        })
        var nextItem = () => {
          ind++
          addItem()
        }
        var addItem = () => {
          var flag = athIds && athIds != null && athIds.length && athIds.length > ind
          if (flag) {
            var athId = athIds[ind]
            var ps = {
              eventId: eventId,
              athId: athId
            }
            me.sys.query(me.sqls.addSingleRegComps_check, ps).then(resCheck => {
              var hadAddedFlag = resCheck && resCheck != null && resCheck.length > 0
              if (hadAddedFlag) {
                resStatus.regIds[athId] = -1
                nextItem()
              } else {
                me.sys.query(me.sqls.addSingleRegComps, ps).then(resAdd => {
                  var flag = resAdd && resAdd != null && resAdd.lastrowid && resAdd.lastrowid > 0
                  resStatus.regIds[athId] = flag ? resAdd.lastrowid : -2
                  me.addRegCompMembers(resAdd.lastrowid, athId).then(_ => {
                    nextItem()
                  })
                })
              }
            })
          } else {
            resStatus.status = 1
            success(resStatus)
          }
        }
        addItem()
      } catch (error) {
        success(resStatus)
      }
    })
  }

  addTeamRegComp (eventId, delegationId, athIds) {
    var me = this
    var resStatus = {
      status: 0,
      regId: 0
    }
    return new Promise((success, faild) => {
      try {
        var getRegCompId = () => {
          return new Promise((su, fa) => {
            try {
              var ps = {
                eventId: eventId,
                delegationId: delegationId
              }
              var regId = 0
              me.sys.query(me.sqls.addTeamRegComps_checkDelegationId, ps).then(resCheck => {
                var hadAddedFlag = resCheck && resCheck != null && resCheck.length > 0
                if (hadAddedFlag) {
                  regId = resCheck[0].regCompID
                  su(regId)
                } else {
                  me.sys.query(me.sqls.addSingleRegComps, ps).then(resAdd => {
                    var flag = resAdd && resAdd != null && resAdd.lastrowid && resAdd.lastrowid > 0
                    regId = resAdd.lastrowid
                    su(regId)
                  })
                }
              })
            } catch (error) {
              su(0)
            }
          })
        }
        getRegCompId().then(regId => {
          if (regId > 0) {
            resStatus = 1
            me.addRegCompMembers(regId, athIds).then(_ => {
              success(resStatus)
            })
          } else {
            success(resStatus)
          }
        })
      } catch (error) {
        success(resStatus)
      }
    })
  }

  addDoubleRegComps (eventId, athIds) {
    var me = this
    var resStatus = {
      status: 0,
      regId: 0
    }
    return new Promise((success, faild) => {
      try {

      } catch (error) {
        success(resStatus)
      }
    })
  }

  getRegCompId (eventId, delegation, aths) {
    var me = this
    var resStatus = {
      status: 0,
      regCompId: 0
    }
    return new Promise((success, faild) => {
      try {

      } catch (error) {
        success(resStatus)
      }
    })
  }

  addRegCompMembers (regCompId, aths) {
    var me = this
    var resStatus = {
      status: 0,
      aths: []
    }
    return new Promise((success, faild) => {
      try {

      } catch (error) {
        success(resStatus)
      }
    })
  }

  checkDoubleFix (eventId, delegation, aths) {
    var me = this
    var res = 0
    try {

    } catch (error) {
      success(resStatus)
    }
    return res
  }
}
export default {
  mounted () {
    var me = this
    try {
      me.$nextTick().then(_ => {
        return me.init()
      }).then(_ => {
        me.refresh()
      })
    } catch (error) {
      console.log(error)
    }
  },

  data () {
    return {
      sqls: {
        path: 'squ/reg/regcomp/',
        getEvents: 'getEvents',
        getDelegations: 'getDelegations',
        getAthletes: 'getAthletes',
        getRegComp: 'getRegComp',
        addRegComp: 'addRegComp',
        addRegCompMember: 'addRegCompMember',
        removeRegComp: 'removeRegComp',

        addRegCompTeam: 'addRegCompTeam',
        addRegCompMemberTeam: 'addRegCompMemberTeam'

      },
      ui: {
        title: {
          icon: 'fa fa-vcard',
          name: 'Regcomp',
          localName: '报名报项'
        },
        regCompTabHeight: 200,
        athleteTabHeight: 200
      },
      events: [],
      eventIndex: 0,
      delegations: [],
      delegationIndex: 0,
      gender: 'X',
      showGender: false,
      regComps: [],
      athletes: []
    }
  },
  methods: {
    init () {
      var me = this
      return new Promise((success, faild) => {
        try {
          me.resize()
          me.sys.query(me.sqls.path + me.sqls.getEvents, {}).then(res => {
            me.events = res
            return me.sys.query(me.sqls.path + me.sqls.getDelegations, {})
          }).then(res => {
            me.delegations = res
            success()
          })
        } catch (error) {
          console.log(error)
        }
      })
    },
    resize () {
      var me = this
      try {
        var h0 = document.getElementById('tabAthleteMain').offsetHeight
        var h1 = document.getElementById('tabRegCompMain').offsetHeight
        me.ui.athleteTabHeight = h0
        me.ui.regCompTabHeight = h1
      } catch (error) {
        console.log(error)
      }
    },
    refresh () {
      var me = this
      try {
        var curEvent = me.events[me.eventIndex]
        me.showGender = curEvent && curEvent != null && curEvent.gender == 'X'
        me.upadateRegComps().then(_ => {
          return me.updateAthletes()
        }).then(_ => {
          console.log('...')
        })
      } catch (error) {
        console.log(error)
      }
    },
    upadateRegComps () {
      var me = this
      return new Promise((success, faild) => {
        try {
          me.regComps = []
          var curEvent = me.events[me.eventIndex]
          var ps = {
            eventId: curEvent.eventId
          }
          var key = me.sqls.path + me.sqls.getRegComp
          me.sys.query(key, ps).then(res => {
            me.regComps = res
            success()
          })
        } catch (error) {
          console.log(error)
        }
      })
    },
    updateAthletes () {
      var me = this
      return new Promise((success, faild) => {
        try {
          me.athletes = []
          var curEvent = me.events[me.eventIndex]
          var curDelegation = me.delegations[me.delegationIndex]
          var ps = {
            eventId: curEvent.eventId,
            delegationId: curDelegation.delegationId
          }
          var key = me.sqls.path + me.sqls.getAthletes
          me.sys.query(key, ps).then(res => {
            me.athletes = res
            console.log(me.athletes)
          })
        } catch (error) {
          console.log(error)
        }
      })
    },
    addRegComp () {
      var me = this
      try {
        var items = me.$refs.athletaTable.selection
        if (items && items.length > 0) {
          var curEvent = me.events[me.eventIndex]
          var curDelegation = me.delegations[me.delegationIndex]
          var athIds = items.map(i => {
            return i.athleteId
          })
          if (curEvent.event.indexOf('SINGLES') >= 0) {
            me.addRegComp_Single(curEvent, curDelegation, athIds)
          } else if (curEvent.event.indexOf('TEAM') >= 0) {
            me.addRegComp_Team(curEvent, curDelegation, items)
          } else if (curEvent.event.indexOf('DOUBLE') >= 0) {
            me.addRegComp_Double(curEvent, curDelegation, athIds)
          }
        } else {
          me.$message.error('please select item.')
        }
      } catch (error) {
        console.log(error)
      }
    },
    addRegComp_Single (curEvent, curDelegation, athIds) {
      var me = this
      try {
        var ind = 0
        var addItem = () => {
          if (ind < athIds.length) {
            var ps = {
              eventId: curEvent.eventId,
              athleteId: athIds[ind]
            }
            var key = me.sqls.path + me.sqls.addRegComp
            me.sys.query(key, ps).then(res => {
              console.log(res)
              ps = {
                regCompID: res.lastrowid,
                athleteID: athIds[ind]
              }
              key = me.sqls.path + me.sqls.addRegCompMember
              return me.sys.query(key, ps)
            }).then(res => {
              console.log(res)
              ind++
              addItem()
            })
          } else {
            console.log('add regcomp...')
            me.refresh()
          }
        }
        addItem()
      } catch (error) {
        console.log(error)
      }
    },
    addRegComp_Team (curEvent, curDelegation, athletes) {
      var me = this
      try {
        var addRegComp = () => {
          var resStatus = {
            status: 0
          }
          return new Promise((success, faild) => {
            try {
              ps = {
                eventId: curEvent.eventId,
                delegationId: curDelegation.delegationId
              }
              key = me.sqls.path + me.sqls.addRegCompTeam
              me.sys.query(ps, key).then(res => {
                if (res && res != null && res.lastrowid > 0) {
                  success({
                    status: 1,
                    regCompId: res.lastrowid
                  })
                } else {
                  success(resStatus)
                }
              })
            } catch (error) {
              success(resStatus)
            }
          })
        }

        var addRegCompMember = (regCompId) => {
          var resStatus = {
            status: 0
          }
          return new Promise((success, faild) => {
            try {
              var index = 0
              var addItem = () => {
                if (index < athletes.length) {
                  var ath = athletes[index]
                  var ps = {
                    regCompID: regCompId,
                    athleteID: ath[index].athleteId
                  }
                  key = me.sqls.path + me.sqls.addRegCompMemberTeam
                  me.sys.query(ps, key).then(res => {
                    index++
                    addItem()
                  })
                } else {
                  resStatus.status = 1
                  success(resStatus)
                }
              }
              addItem()
            } catch (error) {
              success(resStatus)
            }
          })
        }

        addRegComp().then(regCompStatus => {
          if (regCompStatus && regCompStatus.status > 0) {
            addRegCompMember(regCompStatus.regCompId).then(res => {
              me.refresh()
            })
          } else {
            me.$message.error('action faild!')
          }
        })
      } catch (error) {
        console.log(error)
      }
    },
    addRegComp_Double (curEvent, curDelegation, athIds) {
      var me = this
      try {
      } catch (error) {
        console.log(error)
      }
    },
    onPickAthleteGender (gender) {
      var me = this
      try {
        me.gender = gender
      } catch (error) {
        console.log(error)
      }
    },
    getRegId_Single (eventId, delegationId, athletes) {
      var me = this
      var resStatus = {
        status: 0,
        regId: 0
      }
      return new Promise((success, faild) => {
        try {

        } catch (error) {
          success(resStatus)
        }
      })
    },
    getRegId_Tean (eventId, delegationId, athletes) {
      var me = this
      var resStatus = {
        status: 0,
        regId: 0
      }
      return new Promise((success, faild) => {
        try {

        } catch (error) {
          success(resStatus)
        }
      })
    },
    getRegId_Double (eventId, delegationId, athletes) {
      var me = this
      var resStatus = {
        status: 0,
        regId: 0
      }
      return new Promise((success, faild) => {
        try {

        } catch (error) {
          success(resStatus)
        }
      })
    },
    addRegCompMembers (regCompId, athletes) {
      var me = this
      var resStatus = {
        status: 0,
        regId: 0
      }
      return new Promise((success, faild) => {
        try {

        } catch (error) {
          success(resStatus)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
    @import url('../module.less');

    .fullHeight{
        height: 100%;
    }
    .tabGrid{
        display: grid;
        height: 100%;
        grid-template-columns: 61% auto;
        grid-column-gap: 15px;

    }
    .tabPan{
        background-color: #fff;
        display: flex;
        flex-direction: column;
        .tabTools{
            display: flex;
            padding: 0px 15px;
            height: 48px;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #f2f3f9;
            .genderList{
                display: flex;
                height: 30px;
                border:1px solid #0077fe;
                color: #0077fe;
                .gender{
                    width: 28px;
                    height: 28px;
                    line-height: 28px;
                    text-align: center;
                }
                .gender:hover{
                    cursor: pointer;
                }
                .gender.active{
                    background-color: #0077fe;
                    color: #fff;
                }
            }
        }
        .tabFooter{
            padding: 10px ;
            border-top: 1px solid #f2f2f9;
            display: flex;
            .footerAcs{
                display: flex;
                .title{
                    height: 28px;
                    line-height: 28px;
                }

            }
        }
        .tabMain{
            flex: 1;
        }
    }
    .tabRowAcs{
        display: flex;
    }
</style>
